var merge = require('merge');

module.exports = function () {
    if (typeof $ === 'undefined' || typeof $(this.$el).daterangepicker === 'undefined') {
        console.error('Date filters require jquery and daterangepicker');
        return;
    }

    var el;
    var that = this;
    var query = this.vuex ? JSON.parse(JSON.stringify(this.query)) : this.query;
    var columnOptions;
    var dpOptions;

    var search = function (query, e) {
        return that.source == 'client' ? that.search(that.data, e) : that.serverSearch(query, e);
    }

    var datepickerOptions = merge.recursive(this.opts.datepickerOptions, {
        autoUpdateInput: false,
        singleDatePicker: false
    });


    that.datepickerColumns.forEach(function (column) {

        var range = that._getInitialDateRange(column);

        if (range) {

            that._setDatepickerText(column, range.start, range.end);

            range = {
                startDate: range.start,
                endDate: range.end
            }

        } else {
            range = {};
        }


        el = $(that.$el).find("#VueTables__" + $.escapeSelector(column) + "-filter");

        columnOptions = typeof that.opts.datepickerPerColumnOptions[column] !== 'undefined' ?
            that.opts.datepickerPerColumnOptions[column] : {};

        columnOptions = merge.recursive(columnOptions, {
            locale: {
                format: that.dateFormat(column)
            }
        });

        dpOptions = merge(true, datepickerOptions);

        if (columnOptions.ranges === false) {
            dpOptions.ranges = {};
        }

        var drp = el.data('daterangerpicker')

        if (drp) {
            drp.remove()
        }

        el.daterangepicker(merge.recursive(dpOptions, columnOptions, range));

        el.on('apply.daterangepicker', function (ev, picker) {

            query[column] = {
                start: picker.startDate.format('YYYY-MM-DD HH:mm:ss'),
                end: picker.endDate.format('YYYY-MM-DD HH:mm:ss')
            };

            if (!that.vuex)
                that.query = query;

            that._setDatepickerText(column, picker.startDate, picker.endDate);

            that.updateState('query', query);

            search(query, {target: {name: that._getColumnName(column), value: query[column]}});

        });

        el.on('cancel.daterangepicker', function (ev, picker) {

            query[column] = '';

            if (!that.vuex)
                that.query = query;

            picker.setStartDate(moment());
            picker.setEndDate(moment());

            that.updateState('query', query);

            $(this).html("<span class='VueTables__filter-placeholder'>" + that.display('filterBy', {column: that.getHeading(column)}) + "</span>");

            search(query, {target: {name: that._getColumnName(column), value: query[column]}});
        });

    });

}
